import asyncio
from ..utils.browser import AsyncBrowser
from pyquery import PyQuery as pq
import json
import re
import time
import uuid

def ytos(text: str):
    cny_amounts = re.findall(r"¥([\d,]+)", text)
    usd_amount = 0
    for amount in cny_amounts:
        amount_float = float(amount.replace(",", ""))
        usd_amount = amount_float / 7.7

    if usd_amount == 0:
        raise Exception("USD amount not found")
    return usd_amount

async def main(semaphore: asyncio.Semaphore, url: str, proxy: str):
    # 初始化浏览器
    result = {}
    async with semaphore:
        retries = 3
        for attempt in range(retries):
            browser = AsyncBrowser()

            proxy_obj = {}
            if proxy != "":
                proxy_obj = json.loads(proxy)

            try:
                await browser.init_browser(
                    {
                        "executable_path": "resources/chrome-win/chrome.exe",
                        "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
                        "headless": True,
                        "proxy": {
                            "server": f"{proxy_obj["url"]}:{proxy_obj['port']}",
                            "username": proxy_obj["username"],
                            "password": proxy_obj["password"]
                        } if proxy!= "" else None,
                        "args": [
                            "--lang=en-US", 
                            "--blink-settings=imagesEnabled=false",
                            "--disable-extensions",
                            "--disable-gpu",
                            "--disable-software-rasterizer"
                        ]
                    }
                )
                # 打开网页
                await browser.page.goto(url, timeout=100000)
                # 获取页面内容
                doc = pq(await browser.page.content())
                sku_match = re.search(r".*?(\d+)\.aspx", url)
                if sku_match:
                    sku = sku_match.group(1)
                else:
                    raise Exception("SKU not found")
                shuxing1_list_context = []
                try:
                    await browser.page.click("div.ltr-1m7d7di > div > div > div > svg.ltr-sl1u6u")
                    doc = pq(await browser.page.content())
                    shuxing_list = doc("ul.ltr-1euvox7 li")
                    for i, li in enumerate(shuxing_list):
                        if i == 0:
                            continue
                        shuxing_value = pq(li)("p span").text() if pq(li)("p span").text() else ""
                        shuxing1_list_context.append(shuxing_value.strip()) # type: ignore
                except Exception as e:
                    pass
                image_list_context = []
                image_list_obj = doc('div.e1dvjpls0 div')
                image_path = []
                for div in image_list_obj:
                    image = pq(div)("button img")
                    image_url = image.attr("src")
                    if image_url:
                        image_list_context.append(image_url)
                        filename = f"{time.strftime('%Y%m%d%H%M%S')}_{str(uuid.uuid4())[:8]}.jpg"
                        image_path.append(f"/farfetch/{sku}/{filename}")
                huaxian_price = doc('p[data-component="PriceFinalLarge"]').text()
                if huaxian_price != "":
                    huaxian_price = ytos(huaxian_price) # type: ignore
                else:
                    huaxian_price = doc('p[data-component="PriceLarge"]').text()
                    if huaxian_price != "":
                        huaxian_price = ytos(huaxian_price) # type: ignore
                    else:
                        raise Exception("Huaxian price not found")
                
                Category_obj = doc('ol[data-component="Breadcrumbs"] li a')
                Cat1 = ""
                Cat2 = ""
                Gender = ""
                if len(Category_obj) > 0:
                    Gender = pq(Category_obj[0]).text().split(" ")[0] if pq(Category_obj[0]).text() else "" # type: ignore
                if len(Category_obj) > 2:
                    Cat1 = pq(Category_obj[2]).text()
                if len(Category_obj) > 3:
                    Cat2 = pq(Category_obj[3]).text()
                Category = f"{Cat1}>{Cat2}"
                desc = doc("div.exjav154").text()
                desc = f"<div>{desc}</div>"
                desc = desc.replace("\n", "<br>") # type: ignore
                desc = desc.replace("'", "")
                brand = doc("#content > div:nth-child(4) > div.ltr-1jp6yh5 > div.ltr-8c0sef > div > div > div.ltr-1q071fb > div.ltr-ayy0e9 > div > h1").text()
                result =  { 
                    "a_title": doc("title").text().replace("|", "").replace("FARFETCH CN", "").replace("'", ''), # type: ignore
                    "b_short_title": "",
                    "c_image": "|".join(image_path).lstrip('|'),
                    "d_imageUrl": "|".join(image_list_context).lstrip('|'),
                    "e_price": "",
                    "f_huaxian_price": str(huaxian_price),
                    "g_Category": Category,
                    "h1_Cat1": Cat1,
                    "h2_Cat2": Cat2,
                    "h3_Cat3": "",
                    "i1_shuxing1": "size",
                    "i2_shuxing2": "",
                    "i3_shuxing3": "",
                    "j1_shuxing_value1": "|".join(shuxing1_list_context).lstrip('|'),
                    "j2_shuxing_value2": "",
                    "j3_shuxing_value3": "",
                    "k_brand": brand.replace("'", ""), # type: ignore
                    "l_sku": sku,
                    "m_Gender": Gender,
                    "n_color": "",
                    "o_desc": desc.replace("'", ""),
                    "p_tag": "",
                    "q_pageUrl": url,
                    "r_comment1": "",
                    "s_comment2": "",
                    "t_comment3": "",
                    "u_comment4": "",
                    "v_comment5": "",
                    "w_status": "success",
                }
            except Exception as e:
                print(f"Attempt {attempt + 1} failed: {e}")
                if attempt == retries - 1:
                    result =  { 
                        "w_status": "error", 
                        "error": str(e),
                        "q_pageUrl": url
                    }
            finally:
                # 关闭浏览器
                if 'browser' in locals() and browser:
                    await browser.close()
            if result.get("w_status") == "success":
                break  # 如果成功，则退出循环

    return result